package fr.ants.model;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;
import javax.swing.JFrame;

import fr.ants.view.panel.Canvas;

/**
 * <p>
 * Read the card and generate the grid.
 * </p>
 * 
 * @author Thierno BALDE
 */

public class PictureReader extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1348605342334559319L;
	private int xIcon, yIcon;

	public int getxIcon() {
		return xIcon;
	}

	public void setxIcon(int xIcon) {
		this.xIcon = xIcon;
	}

	public int getyIcon() {
		return yIcon;
	}

	public void setyIcon(int yIcon) {
		this.yIcon = yIcon;
	}

	/** Load grid */
	public int[][] loadGrid(File file) {
		return readPixels(file.getAbsolutePath());
	}

	/**
	 * @param image
	 */

	private int[][] readPixels(String image) {
		int[][] maGrille = null;
		try {
			BufferedImage img = ImageIO.read(new File(image));
			maGrille = new int[img.getHeight() / Canvas.NODE_SIZE][img.getWidth() / Canvas.NODE_SIZE];
			int cptX = 0;
			int cptY = 0;

			/** read the pixels of the image */
			for (int i = 0; i < (img.getWidth()-Canvas.NODE_SIZE); i = i + Canvas.NODE_SIZE) {
				for (int j = 0; j < (img.getHeight()-Canvas.NODE_SIZE); j = j + Canvas.NODE_SIZE) {

					/** get color of each pixel */
					Color pixelcolor = new Color(img.getRGB(i, j));

					/** get RGB values of the color */
					int r = pixelcolor.getRed();
					int g = pixelcolor.getGreen();
					int b = pixelcolor.getBlue();

					double calc = (r + g + b);
					if (calc > 0) {

						maGrille[cptX][cptY] = (int) (((255 - calc / 3) / 255) * 100);
					} else {
						maGrille[cptX][cptY] = 0;
					}
					cptX++;
				}
				cptX = 0;
				cptY++;
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return maGrille;
	}

}